package com.example.dell.fastshopping.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.example.dell.fastshopping.MyApplication;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.ApiService;
import com.example.dell.fastshopping.network.NetCallback;
import com.example.dell.fastshopping.network.RetrofitClient;
import com.example.dell.fastshopping.utils.KLog;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by ${YSH} on 2019/5/28.
 * 描述        ${TODO}
 * <p>
 * 更新者       $author$
 * 更新时间     $Data$
 * 描述         ${TODO}
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI api;
    private ApiService apiService;
    private static int taskId;

    public static void setTaskID(int id) {
        taskId = id;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weixin_back);
        initData();
        KLog.e("123");
    }

    @Override
    public void onReq(BaseReq baseReq) {
        KLog.e("baseReq");
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        KLog.e("resp");
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK: {
                shareToService();
            }
            break;
        }
        finish();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        initData();
    }

    private void initData() {
        api = MyApplication.getWxAPI();
        api.handleIntent(getIntent(), this);
    }

    private void shareToService() {
        if (apiService == null)
            apiService = RetrofitClient.getInstance().create(ApiService.class);

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", taskId);
        map.put("weixinShare", 1);
        String s = new GsonBuilder().create().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), s);
        RetrofitClient.execute(apiService.share(body), new NetCallback() {
            @Override
            public void netCallback(Object o) {
                finish();
            }
        });
    }
}
